package com.execjar.pound;

import com.execjar.fun.FunctionCalc;
import com.execjar.fun.FunctionParse;
import com.execjar.fun.FunctionPound;
import com.execjar.fun.FunctionSleep;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhuzi 2022/8/18 22:39
 */
@Slf4j
public class PoundRead {


    public static void loopRead(EquDTO equDTO, int loopNum, int validNumber, int netErrNum,
                                int parseErrNum, int readLength, FunctionPound<String, String, Integer, byte[]> funcPound,
                                FunctionParse<byte[], Integer> funParseRead, FunctionSleep funSleep, FunctionCalc<List<Integer>, Integer> funCalc) {

        // 记录错误次数
        int tmpnetErrNum = 0;
        int tmpparseErrNum = 0;
        String pound = "";
        List<Integer> wList = new ArrayList<>();
        Boolean netErr = Boolean.TRUE;
        for (int i = 0; i < loopNum; i++) {
            try {
                byte[] tcpRead = funcPound.apply(equDTO.getEqpIp(), equDTO.getEqpPort(),
                        readLength);

                Integer readPound = funParseRead.apply(tcpRead);
                log.info("解析次数[{}]结果[{}]", i, readPound);
                pound = String.valueOf(readPound);
                wList.add(readPound);
                // 这里也可以提取出去
                if (wList.size() == validNumber) {
                    System.out.println("读取次数够了");
                    break;
                }
            } catch (Exception e) {
                log.error("读取地磅-解析地磅错误-第[{}]次", i, e);
                tmpparseErrNum++;
            }
            if (tmpnetErrNum > netErrNum) {
                log.error("读取次数过多");
                throw new RuntimeException("err");
            }

            funSleep.sleep();
        }
        if (loopNum == 1) {
            //只读一次 读取不到,是网络异常了
            if (StringUtils.isBlank(pound)) {
                throw new RuntimeException("读取一次出现错误");
            }


            equDTO.setResult(pound);
        } else {
            Integer max = funCalc.apply(wList);
            log.info("计算完成[{}]", max);
            equDTO.setResult(String.valueOf(max));
        }
    }

}
